package tasks.leetcode;

/**
 * 最长回文子串
 * https://leetcode.cn/problems/longest-palindromic-substring/
 */
public class TaskLongestPalindrome {
    public static void main(String[] args) {
        String s = new TaskLongestPalindrome().longestPalindrome("ba");
        System.out.println(s);
    }

    /***
     * 实现思路
     * 两层循环；
     * 外循环进行索引的遍历
     * 使用s.substring 的方式来获取最终的字符串，避免返回的字符串是空的场景
     * @param s
     * @return
     */
    public String longestPalindrome(String s) {
        if (s == null) {
            return null;
        }
        if (s.length() <= 1) {
            return s;
        }
        int length = s.length();
        int begin = 0;
        int currentMax = 1;
        for (int i = 0; i < length; i++) {
            for (int j = i + 1; j < length; j++) {
                int currentLength = j - i + 1;
                String currentStr = s.substring(i, i + currentLength);
                if (currentLength > currentMax && istTargetStr(currentStr)) {
                    currentMax = currentLength;
                    begin = i;
                }
            }
        }
        return s.substring(begin, begin + currentMax);
    }

    private boolean istTargetStr(String currentStr) {
        int left = 0;
        int right = currentStr.length() - 1;
        while (left <= right) {
            if (currentStr.charAt(left) != currentStr.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}
